//
//  LSChatCircleVController.m
//  LookScore
//
//  Created by wr on 2017/12/5.
//  Copyright © 2017年 ChongQingXunTiCompany. All rights reserved.
//



#import "LSChatTopView.h"
#import "LSCustomHeaderView.h"
#import "LSChatCircleCell.h"
#import "LSChatCircleVController.h"
#import "ConversationDetailController.h"
#import "GreenBattlefieldViewController.h"
#import "LSChatCircleModel.h"
#import "LSTopicCircleModel.h"
#import "LSOtherHomePageViewController.h"
#import "LSPersonalHomePageVController.h"
#import "YBPopupMenu.h"
@interface LSChatCircleVController ()<UITableViewDelegate,UITableViewDataSource,YBPopupMenuDelegate>

@property(strong,nonatomic)UITableView *tableView;

@property(strong,nonatomic)NSMutableArray *modelArray;


@property (nonatomic, assign) NSInteger selectType;//选择话题类型

@property (nonatomic, strong) NSMutableArray * topicModelArr;
@property (nonatomic, assign) NSInteger tag;

@property (nonatomic, assign) NSInteger queryCircleId;
@end

@implementation LSChatCircleVController{
    NSInteger _pageCount;
    NSString * _tokenStr;
    LSChatTopView * _chatView;
    NSIndexPath *_indexPath;
    
}

- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]init];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor =LSBackGroundColor;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _tableView;
}
- (NSMutableArray *)modelArray{
    if(!_modelArray){
        _modelArray = @[].mutableCopy;
    }
    return _modelArray;
}

- (NSMutableArray *)topicModelArr{

    if (!_topicModelArr) {
        _topicModelArr = @[].mutableCopy;
    }
    return _topicModelArr;
}


- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title=@"圈子";
   _tokenStr = [LSAccountArchive isLogin] ? [LSAccountArchive account].Cid : @"";
    self.view.backgroundColor = LSTitleWhiteColor;
    self.selectType = 1;
    [self.view addSubview:self.tableView];
    [self initPagerView];
    [self loadTopicCircleData];
    [self loadData:YES];
    
    self.tableView.sd_layout
    .leftEqualToView(self.view)
    .topSpaceToView(self.view, 0)
    .rightEqualToView(self.view)
    .bottomEqualToView(self.view);
    
    
    LSRefreshHeaderView *header = [LSRefreshHeaderView headerWithRefreshingBlock:^{
        [self loadData:YES];
        [self loadTopicCircleData];
        
    }];
    self.tableView.mj_header = header;// 设置header
    [header beginRefreshing];
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        [self loadData:NO];
    }];
    self.tableView.mj_footer.ignoredScrollViewContentInsetBottom = HOME_INDICATOR_HEIGHT;
    [notifiCenter addObserver:self selector:@selector(updateData) name:@"LOADCIRCLEDATA" object:nil];
    [notifiCenter addObserver:self selector:@selector(loginOut) name:@"LOGIONOUT" object:nil];
    [notifiCenter addObserver:self selector:@selector(updateData) name:@"LOGINSUCCESS" object:nil];
    

    if (@available(iOS 11.0, *)) {
        
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
    }
  

}
#pragma mark --加载数据源
- (void)loadTopicCircleData{
    
    [LSHttpEnclosureTool GET:LSTOPICCIRCLE parameters:nil resBlock:^(id responseObject) {
        if (responseObject) {
            [self.topicModelArr removeAllObjects];
            for (NSDictionary * dict in responseObject[@"CircleList"]) {
                LSTopicCircleModel * model = [LSTopicCircleModel mj_objectWithKeyValues:dict];
                [self.topicModelArr addObject:model];
            }
            _chatView.dataArray = self.topicModelArr;
            MyLog(@"topoccount == %ld",[responseObject[@"CircleList"] count]);
        }
    }];
    
    
}

- (void)loadData:(BOOL)refresh{
    if (refresh) {
        _pageCount = 0;
    }else{
        _pageCount += 1;
    }
    NSDictionary * parameters = @{@"type":@(self.selectType),@"pageIndex":@(_pageCount),@"cid":_tokenStr,@"circleId":@""};
    [LSHttpEnclosureTool GET:LSTOPICLIST parameters:parameters resBlock:^(id responseObject) {
//        MyLog(@"111 ---- %@",responseObject);
        if (responseObject) {
            if (refresh) {
                [self.modelArray removeAllObjects];
            }
            for (NSDictionary * dict in responseObject[@"TopicList"]) {
                LSChatCircleModel *model = [LSChatCircleModel mj_objectWithKeyValues:dict];
                [self.modelArray addObject:model];
            }
        }else{
            _pageCount -= 1;
        }
        [self.tableView reloadData];
        [CommonClass endRefreshing:self.tableView];
    }];
    
}

- (void)loginOut{
    
    _tokenStr = @"";
    [self loadData:YES];
    
    
}

- (void)updateData{
    _tokenStr = [LSAccountArchive isLogin] ? [LSAccountArchive account].Cid : @"";
    [self loadData:YES];
    [self loadTopicCircleData];
    
}

#pragma mark 🔥 tableViewDelegate tableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.modelArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    LSChatCircleModel *  model = self.modelArray[indexPath.row];
    if ([model.ImgUrlStr componentsSeparatedByString:@","].count == 1 && model.ImgUrlStr.length>0) {
        return [self.tableView cellHeightForIndexPath:indexPath model:model keyPath:@"model" cellClass:[LSChatCircleOneImageViewCell class] contentViewWidth:[tableView cellContentViewWith]];
    }else{
        return [self.tableView cellHeightForIndexPath:indexPath model:model keyPath:@"model" cellClass:[LSChatCircleCell class] contentViewWidth:[tableView cellContentViewWith]];
    }
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    LSChatCircleModel * model = self.modelArray[indexPath.row];
    if ([model.ImgUrlStr componentsSeparatedByString:@","].count == 1 && model.ImgUrlStr.length>0) {
        LSChatCircleOneImageViewCell * cell = [LSChatCircleOneImageViewCell ChatCircleOneImageViewCellByTableView:tableView];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.model = model;
        KWeakSelf(self);
        cell.block = ^(UIButton *sender) {
            [weakself reportAction:indexPath withSender:sender];
//            [weakself attentionAction:indexPath withSender:sender];
        };
        
        cell.clickedImageViewBlock = ^{
            if ([LSAccountArchive isLogin]) {
                if ([[LSAccountArchive account].Cid isEqualToString:model.UserCid]) {
                    LSPersonalHomePageVController * personalVc = [[LSPersonalHomePageVController alloc] init];
                    personalVc.userCid = model.UserCid;
                    [self.navigationController pushViewController:personalVc animated:YES];
                }else{
                    LSOtherHomePageViewController * otherVC = [[LSOtherHomePageViewController alloc] init];
                    otherVC.userCid = model.UserCid;
                    [self.navigationController pushViewController:otherVC animated:YES];
                }
            }else{
                [self presentLoginVC];
            }
        };
        return cell;
    }else{
        LSChatCircleCell *cell=[LSChatCircleCell ChatCircleTableViewCellByTableView:tableView];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.model = model;
        KWeakSelf(self);
        cell.block = ^(UIButton *sender) {
//            [weakself attentionAction:indexPath withSender:sender];
            [weakself reportAction:indexPath withSender:sender];
        };
        cell.clickedImageViewBlock = ^{
            if ([LSAccountArchive isLogin]) {
                LSOtherHomePageViewController * otherVC = [[LSOtherHomePageViewController alloc] init];
                otherVC.userCid = model.UserCid;
                [self.navigationController pushViewController:otherVC animated:YES];
            }else{
                [self presentLoginVC];
            }
            
        };
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    LSChatCircleModel * model = self.modelArray[indexPath.row];
    ConversationDetailController *detailVC = [[ConversationDetailController alloc]init];
    detailVC.TopicId = model.Id;
    detailVC.cid = _tokenStr;
    [self.navigationController pushViewController:detailVC animated:YES];
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    NSString *cellId = [NSString stringWithFormat:@"section:%ld ChatCircleView ",section];
    LSCustomHeaderView *_Nullable headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:cellId];
    if (!headerView) {
        headerView = [[LSCustomHeaderView alloc]initWithReuseIdentifier:cellId style:KTableViewHeaderScrollerStyle];
        [headerView setScrolArray:@[@"热门",@"精选",@"关注"] spaceWidth:30 titleColor:[CommonClass colorWithHexString:@"#191919"] seletedColor:LSSubColore5735e with:_tag];
        KWeakSelf(headerView);
        headerView.butonActionBlock = ^(NSInteger tag) {
//            MyLog(@"%ld",tag);
            if (tag == 2) {
                if ([LSAccountArchive isLogin]) {
                    self.selectType = tag + 1;
                    _tag = tag;
                    [self loadData:YES];
                }else{
                    [MBProgressHUD showOnlyMessage:@"请登录" afterDelay:1.5];
                    weakheaderView.selectTag = _tag;
                }
            }else{
                self.selectType = tag + 1;
                _tag = tag;
                [self loadData:YES];
            }
        };
        headerView.contentView.backgroundColor=[UIColor whiteColor];
        headerView.lineColor=LSNavMainColor;
    }
    return headerView;   
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 42;
}

//- (NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath{
//    UITableViewRowAction *deleteAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:@"删除" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
//        MyLog(@"点击了删除");
//    }];
//
//
////    UITableViewRowAction *editAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@"编辑" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
////        MyLog(@"点击了编辑");
////    }];
////    editAction.backgroundColor = [UIColor grayColor];
////    return @[deleteAction, editAction];
//    return @[deleteAction];
//}

//- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
//    editingStyle = UITableViewCellEditingStyleDelete;
//}

//#pragma mark -- 关注按钮点击事件
//- (void)attentionAction:(NSIndexPath *)indexPath withSender:(UIButton *)sender{
//
//    LSChatCircleModel * model = self.modelArray[indexPath.row];
//    if ([LSAccountArchive isLogin]) {
//        sender.enabled = NO;
//        [LSHttpEnclosureTool POST:LSUserAttention parameters:@{@"cid":model.UserCid,@"fanCid":[LSAccountArchive account].Cid} resBlock:^(id responseObject) {
////            MyLog(@"%@",responseObject);
//            if ([responseObject integerValue] == 1) {
//
//            }
//            sender.selected = !sender.selected;
//            sender.enabled = YES;
//            [notifiCenter postNotificationName:@"LOADCIRCLEDATA" object:nil];
//            [self loadData:YES];
//        }];
//    }else{
//        [self presentLoginVC];
//    }
//}
#pragma mark - YBPopupMenuDelegate
- (void)ybPopupMenuDidSelectedAtIndex:(NSInteger)index ybPopupMenu:(YBPopupMenu *)ybPopupMenu{

    
    LSChatCircleModel * model = self.modelArray[_indexPath.row];
    MyLog(@"%ld",_indexPath.row);
    if ([LSAccountArchive isLogin]) {

        [LSHttpEnclosureTool POST:LSAddUserScreenTopic parameters:@{@"usercid":[LSAccountArchive account].Cid,@"topicId":[NSString stringWithFormat:@"%ld",(long)model.Id]} resBlock:^(id responseObject) {
            MyLog(@"111 --- %@",responseObject);
            if ([responseObject[@"IsSuccess"] integerValue] == 1) {
                [self.modelArray removeObjectAtIndex:_indexPath.row];
                [self.tableView beginUpdates];
                [self.tableView deleteRowsAtIndexPaths:@[_indexPath] withRowAnimation:UITableViewRowAnimationFade];
                [self.tableView endUpdates];
                [self.tableView reloadData];
            }else{
                [MBProgressHUD showOnlyMessage:@"屏蔽失败" afterDelay:1.5f];
            }

        }];
    }else{
        [self presentLoginVC];
    }

    
}
#pragma mark -- 举报按钮点击事件
- (void)reportAction:(NSIndexPath *)indexPath withSender:(UIButton *)sender{
    
    [YBPopupMenu showRelyOnView:sender titles:@[@"屏蔽"] icons:nil menuWidth:120 delegate:self];
    _indexPath = indexPath;
}

#pragma mark 🔥  事件
-(void)chatTopView:(KChatTopViewEvent )type{
    LSTopicCircleModel * model = self.topicModelArr[type];
    GreenBattlefieldViewController * greenBattlefieldVC = [[GreenBattlefieldViewController alloc] init];
    greenBattlefieldVC.tokenStr = _tokenStr;
    greenBattlefieldVC.model = model;
    [self.navigationController pushViewController:greenBattlefieldVC animated:YES];
//    switch (type) {
//        case KChatTopViewEventBattlefield:{
//
//        }
//            break;
//        case KChatTopViewEventSpinage:{
//
//        }
//
//            break;
//
//        case KChatTopViewEventSuggest:{
//
//        }
//
//            break;
//
//
//        default:
//            break;
//    }
    
}
#pragma mark 🔥 UI
- (void)initPagerView{

    UIView * bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, LSScreenWidth, LSScareValue(96, LSScreenWidth))];
    KWeakSelf(self);
    _chatView = [[LSChatTopView alloc]initWithFrame:CGRectMake(0, 0, LSScreenWidth, LSScareValue(86, LSScreenWidth))];
    _chatView.chatTopBlock = ^(KChatTopViewEvent type) {
        [weakself chatTopView:type];
    };
//    [self.view addSubview:chatView];
    [bgView addSubview:_chatView];
    self.tableView.tableHeaderView = bgView;
}

- (void)presentLoginVC{
    LSLoginVController *loginVC=[[LSLoginVController alloc]init];
    [self presentRootViewController:loginVC animated:YES completion:nil];
    loginVC.loginSuccessBlock = ^{
        [self.tableView reloadData];
        _tokenStr = [LSAccountArchive account].Cid;
    };
    
}
- (void)dealloc{
    
    [notifiCenter removeObserver:self];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
